import {lyric} from "@src/services/music.ts";
import {useRequest} from "ahooks";
import {useEffect, useRef, useState} from "react";
import "./index.scss"
import {useAudioPlayer} from "@src/store/music.ts";

interface LyricProps {
    id: number;
}

// 歌词对象类型
type LyricItem = {
    time: number;
    words: string;
}

// 解析时间字符串为秒
const parseTime = (timeStr: string): number => {
    const parts = timeStr.split(':');
    return +parts[0] * 60 + +parts[1];
};

// 解析歌词字符串
const parseLrc = (lrc: string): LyricItem[] => {
    const lines = lrc.split('\n');
    const result: LyricItem[] = [];
    for (let i = 0; i < lines.length; i++) {
        const str = lines[i];
        const parts = str.split(']');
        const timeStr = parts[0].substring(1);
        const obj: LyricItem = {
            time: parseTime(timeStr),
            words: parts[1],
        };
        result.push(obj);
    }
    return result;
};

const Lyric = ({id}: LyricProps) => {
    const {audio} = useAudioPlayer()
    const lyricApi = useRequest(lyric, {manual: true})
    const [lrcData, setLrcData] = useState<LyricItem[]>([]);
    const ulRef = useRef<HTMLUListElement>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    const [highlightIndex, setHighlightIndex] = useState(-1);

    useEffect(() => {
        lyricApi.runAsync(id).then((data) => {
            setLrcData(parseLrc(data.lrc.lyric))
        }).catch((error) => {
            console.error('获取歌词失败:', error);
        });
    }, [id]);

    useEffect(() => {
        audio.addEventListener('timeupdate', setOffset);
        return () => {
            audio.removeEventListener('timeupdate', setOffset);
        };
    }, [lrcData]);

    // 计算高亮歌词的下标
    const findIndex = (): number => {
        const curTime = audio.currentTime || 0;
        for (let i = 0; i < lrcData.length; i++) {
            if (curTime < lrcData[i].time) {
                return i - 1;
            }
        }
        return lrcData.length - 1;
    };

    // 设置 ul 元素的偏移量
    const setOffset = () => {
        if (ulRef.current && containerRef.current) {
            const containerHeight = containerRef.current.clientHeight;
            const liHeight = ulRef.current.children[0]?.clientHeight || 0;
            const maxOffset = ulRef.current.clientHeight - containerHeight;

            const index = findIndex();
            setHighlightIndex(index);
            let offset = liHeight * index + liHeight / 2 - containerHeight / 2;
            if (offset < 0) {
                offset = 0;
            }
            if (offset > maxOffset) {
                offset = maxOffset;
            }
            ulRef.current.style.transform = `translateY(-${offset}px)`;
        }
    };


    return (
        <div className="container lyric" ref={containerRef}>
            <ul ref={ulRef}>
                {lrcData.map((item, index) => (
                    <li key={index} className={index === highlightIndex ? 'active' : ''}>
                        {item.words}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default Lyric;